package cn.kgc.javaweb.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author: mosin
 * @version: v1.0  2022/5/31
 */
@WebServlet("/file")
public class FileServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getParameter("method");

        switch (method){
            case "upload":
                upload(req, resp);
                break;
            case "download":
                download(req, resp);
                break;
        }
    }

    //文件上传
    protected void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //创建文件上传工厂对象
        FileItemFactory fileItemFactory = new DiskFileItemFactory();
        //创建文件上传组件
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

        try {
            //使用文件上传组件 解析请求对象    List<FileItem>    FileItem  封装了表单中的数据
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
            // 遍历集合 寻找哪个item是文件上传的Item
            for (FileItem item : fileItems) {
                //判定item是否是文件数据      isFormField() 判定是否是普通的表单数据
                if( !item.isFormField()){
                    // 将文件进行上传操作
                    //创建文件上传路径
                    File file = new File("D:\\upload");
                    //获取上传文件的名字
                    String name = item.getName();
                    System.out.println("name = " + name);
                    //处理文件的名字  文件的名字唯一
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    //获取文件的后缀 扩展名  .jpg  .png
                    String extend = name.substring(name.lastIndexOf("."));
                    //拼接文件在磁盘中保存的名字
                    String finalName =uuid+extend;
                    //文件上传
                    item.write(new File(file, finalName));
                    System.out.println("文件上传成功！");

                    // TODO 将文件的名字和uuid名字存储到数据库

                    HttpSession session = req.getSession();
                    session.setAttribute("fileName", name);
                    session.setAttribute("uuid", finalName);

                    // 将页面重定向到下载页 download.jsp
                    resp.sendRedirect(req.getContextPath()+"/download.jsp");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件上传出错了！！！");
        }
    }

    //文件下载
    protected void download(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取下载文件的uuid
        String uuid = req.getParameter("uuid");
        //创建输入流 读取磁盘中存储的文件
        FileInputStream fileInputStream = new FileInputStream(new File("D:\\upload\\" + uuid));
        //设置以附件形式打开  不设置 浏览器会默认打开改文件 不会以附件的形式下载
        resp.setHeader("Content-Disposition", "attachment; filename="+uuid);
        //获取输出流对象 将文件写出
        ServletOutputStream outputStream = resp.getOutputStream();
        //使用工具类 实现流的对拷
        IOUtils.copy(fileInputStream, outputStream);
    }
}
